//
//  MBDGroupQRCodePicker.swift
//  MasterBoy
//
//  Created by kyson on 2024/8/28.
//

import Foundation

import UIKit
import LGAlertView
import SnapKit
import Toast_Swift
import TZImagePickerController

typealias KQRCompletionBlock = (_ image : UIImage, _ imagePath : String, _ praisedImageUrlString : String) ->()


class MBDGroupQRCodePicker : NSObject {
    var hostVC : MBDBaseViewController!
    var compltion: KQRCompletionBlock?
    
    init(hostVC: MBDBaseViewController) {
        self.hostVC = hostVC
    }
        
    func showPicker(){
        // 设置源为相机
        let alert = LGAlertView(title: nil, message: nil, style: .actionSheet, buttonTitles: ["拍照","从手机相册选择"], cancelButtonTitle: "取消", destructiveButtonTitle: nil, actionHandler: {alert,index, title in
            
            if index == 0 {
                self.takePhoto()
            } else if 1 == index {
                self.selectPhoto()
            }

        }, cancelHandler: { alertView in
            
        })
        alert.buttonsHeight = 40
        alert.cancelButtonOffsetY = 40
        alert.show()
        
    }
    
    func takePhoto(){
        let picker = UIImagePickerController()
        picker.sourceType = .camera
        picker.delegate = self
        self.hostVC.present(picker, animated: true)
    }
    
    func selectPhoto() {
        
        let imagePickerVc = TZImagePickerController(maxImagesCount: 1, columnNumber: 4, delegate: nil)
        imagePickerVc!.modalPresentationStyle = .fullScreen
        imagePickerVc!.allowCrop = true
        let cropHeight =  UIScreen.main.bounds.width * MBDPickerConfig.ratioGroupQRCodeHeightWidth
        let originY = UIScreen.main.bounds.height / 2 - cropHeight / 2
        imagePickerVc!.cropRect = CGRect(x: 0, y: originY , width: UIScreen.main.bounds.width, height:cropHeight)
        imagePickerVc!.didFinishPickingPhotosHandle = { (photos,assets,isSelectOriginalPhoto) in
            
            let image = photos!.first
            guard let prasedContent = QRCodeUtils.pictureQRCodeResult(image: image) else {
                self.hostVC.view.makeToast("您上传的二维码有误！")
                return
            }
            
            if false == prasedContent.isBlank {
                self.uploadPicture(image: photos!.first!)
            } else {
                self.hostVC.view.makeToast("您上传的二维码有误！")
            }
            
        }
        self.hostVC.present(imagePickerVc!, animated: true, completion: nil)
    }
    
}


extension MBDGroupQRCodePicker : UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        picker.dismiss(animated: true, completion: nil)
    }
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        picker.dismiss(animated: true, completion: nil)
        guard let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage else{
            return
        }
        
        guard let prasedContent = QRCodeUtils.pictureQRCodeResult(image: image) else {
            self.hostVC.view.makeToast("您上传的二维码有误！")
            return
        }
        
        if true == prasedContent.isBlank {
            self.hostVC.view.makeToast("您上传的二维码有误！")
            return
        }
        
        TZImageManager.default().savePhoto(with: image) { assert, error in
            if (nil != error) {
                self.hostVC.view.makeToast("上传失败！")
            } else {
                let model = TZImageManager.default().createModel(with: assert)
                let imagePickerVc = TZImagePickerController.init(cropTypeWith: model?.asset, photo: image) { image, assert in
                    self.uploadPicture(image: image!)
                }
                
                imagePickerVc!.modalPresentationStyle = .fullScreen
                imagePickerVc!.allowCrop = true
                let cropHeight =  UIScreen.main.bounds.width * MBDPickerConfig.ratioGroupQRCodeHeightWidth
                let originY = UIScreen.main.bounds.height / 2 - cropHeight / 2
                imagePickerVc!.cropRect = CGRect(x: 0, y: originY , width: UIScreen.main.bounds.width, height:cropHeight)
                self.hostVC.present(imagePickerVc!, animated: true, completion: nil)
                
            }

        }
        
    }
    
    
    func uploadPicture(image : UIImage){
        self.hostVC.startIndicatorAnimating()

        let imageData = image.compressImage()
        
        //先上传图片，再更新用户信息
        self.uploadPic(imageData: imageData) { error, picPath in
            //上传后判断结果
            if nil == error {
                //更新信息后判断结果
                let prasedContent = QRCodeUtils.pictureQRCodeResult(image: image)
                
                if let cp = self.compltion {
                    cp(image,picPath!,prasedContent!)
                }
                
            } else {
                self.hostVC.stopIndicatorAnimationg()
                self.hostVC.view.makeToast(error?.localizedDescription)

            }
        }
    }
    
    func uploadPic(imageData : Data,completionHandler: @escaping (NSError?,String?) -> Void) {
        MBDHttpClient.shared.doUploadFileRequest("/oss/upload", data: imageData, fileName: "file").httpClientResponse { error, response in
            debugPrint(error ?? "")
            
            if nil == error {
                let rawDict = response?.rawDict
                let data : String = rawDict?["data"] as! String

                //返回值
                if data.isBlank {
                    completionHandler(error,nil)
                } else {
                    completionHandler(nil,data)
                }
                
            } else {
                //返回值
                completionHandler(error,nil)
            }
        }
    }
    
}
